﻿


function createFeature(coordinates, type, id,  reserveName) {
	
	var feature = null;
	 if (type == 'Point') {
         feature = new ol.Feature({
            geometry: new ol.geom.Point(coordinates),
            id: id,          
            type:'Feature',
            name:reserveName,
            coordinates: coordinates
        });
        feature.setId(id);
    } 
    else if (type == 'Line') {
        feature = new ol.Feature({
        	geometry: new ol.geom.LineString(coordinates),
           id: id,          
            type:'Feature',
            name:reserveName,
            coordinates: coordinates
        });
    } 
    else if (type == 'Poly') {
        feature = new ol.Feature({
        	geometry: new ol.geom.Polygon(coordinates),
           id: id,          
            type:'Feature',
            name:reserveName,
            coordinates: coordinates
        });
	 }
	 if(feature){
	 	feature.setId(id);
	 }
      
	/*			
	var feature = {
				 	type: 'Feature',
				 	id: id,				 	
				 	//'properties':properties,
				 	properties:{
				 		name: "1234689"
				 	},
    			geometry: {
      			type: type,
      			coordinates: coordinates
      		}
			};*/
			return feature;
}


function createPointFeature(coordinates, id, properties) {
	
	/*
		var properties_f = {
				'name' : '124',
				'position' : [[4e6, -2e6], [8e6, 2e6]],
				'info' : '12345678'
			};*/
			var cd = Array ();
			cd = coordinates.split(",");
			
			var lon = parseFloat(cd[0]);
			var lat = parseFloat(cd[1]);
			
	var feature = {
				 	'type': 'Feature',
				 	'id': id,
				 	
				 	//'properties':properties,
				 	'properties':{
				 		'name': coordinates
				 		},
    			'geometry': {
      		'type': 'Point',
      		'coordinates': [lon,lat]
      	}
			};
			return feature;
}


function createLineFeature(coordinates, id, properties) {
	
	/*
		var properties_f = {
				'name' : '124',
				'position' : [[4e6, -2e6], [8e6, 2e6]],
				'info' : '12345678'
			};*/
			
			
			var szCoord = Array ();
			szCoord = coordinates.split(";");
			
			var szPoint = Array ();
			for (var i = 0; i < szPoint.length;  i++) {
				 // code to be executed
				 var coord = [];
				 coord = szPoint[i].split(",");
				 var point = [parseFloat(coord[0]),parseFloat(coord[1])];
				 szPoint.push(point);
			}
					
	var feature = {
				 	'type': 'Feature',
				 	'id': id,
				 	
				 	//'properties':properties,
				 	'properties':{
				 		'name': coordinates
				 		},
    			'geometry': {
      		'type': 'LineString',
      		'coordinates': szPoint
      	}
			};
			return feature;
}

function createPolyFeature(coordinates, id, properties) {
	
	/*
		var properties_f = {
				'name' : '124',
				'position' : [[4e6, -2e6], [8e6, 2e6]],
				'info' : '12345678'
			};*/
			
			var geoCollect = Array ();
			
			var szCoord = Array ();
			szCoord = coordinates.split(";");
			
			var szPoint = Array ();
			for (var i = 0; i < szPoint.length;  i++) {
				 // code to be executed
				 var coord = [];
				 coord = szPoint[i].split(",");
				 var point = [parseFloat(coord[0]),parseFloat(coord[1])];
				 szPoint.push(point);
			}
			geoCollect.push(szPoint);
					
	var feature = {
				 	'type': 'Feature',
				 	'id': id,
				 	
				 	//'properties':properties,
				 	'properties':{
				 		'name': coordinates
				 		},
    			'geometry': {
      		'type': 'Polygon',
      		'coordinates': geoCollect
      	}
			};
			return feature;
}

function createFeatureCollection(features){
		
	var featureCollection = {  
    'type': 'FeatureCollection',  
    'features': features  
  }; 
  return featureCollection;
}


//创建点类features——json
function createFeaturesJson(datasource){
	
	if(datasource){
		
		featureList = new Array();
		
		for(var i =0; i< datasource.length; i++){
			
			 var fea = createPointFeature(datasource[i], i);
			 featureList.push(fea);			
		}
		
		var features_json = createFeatureCollection(featureList);
		
		return features_json;
	}
	
}

//======================获取后台图层信息Begin====================//

//获取表图层
function getTableData(urlInfo){

	$.ajax({
		type: 'get',
		datatype:'json',
		url: urlInfo,
		success: function(data, textStatus, xhr){
			if (data) {
               loadLayerSpaceData(data, layer);
				}
			},
		error: function(error){
			alert('获取表格数据信息失败！');
		}
	});
}


//获取图层空间数据
function loadLayerSpaceData(data, layer){

	if (layer) {
		//清空地图上的矢量图
		layer.getSource().clear();
	}

	if (data) {
		 var dataJson = createFeaturesJson(data);
                              
     var featues = (new ol.format.GeoJSON()).readFeatures(geojsonObject);
               
     layer.getSource().addFeatures(features);		
	}
}

//动态在地图上添加Feature
function addFeature(layer, id, coordinates, type, name, style){
	
    var feature = createFeature(coordinates, type, id, name);   
    /*
 	$.get(url, function(data){
		var style = new ol.style.Style({
			  stroke: new ol.style.Stroke({
			      color: data.color,
			      width: Number(data.geoSize.substring(0,data.geoSize.length-2))
			  }),
			  image: new ol.style.Circle({
	            radius: Number(data.geoSize.substring(0,data.geoSize.length-2)),
	            fill: new ol.style.Fill({
	                color: data.color
	            })
	          })
		});
		baseVectorLayer.setStyle(style);
	});*/
    feature.setStyle(style);
    layer.getSource().addFeature(feature);	
    return feature;
}

///删除feature
function deleteFeature(layer, id){
	
    var feature = layer.getSource().getFeatureById(id);		
    if(feature){
    	layer.getSource().removeFeature(feature);
    }
}



var drawGeom = {
	 /**
     * Currently drawn feature.
     * @type {ol.Feature}
     */
    drawend: false,
	  /**
     * Currently drawn feature.
     * @type {ol.Feature}
     */
    sketch: null,
    /**
     * Currently drawn feature.
     * @type {ol.geojson}
     */
    geojson: null,
     /**
     * Currently drawn type
     * @type {point\line\poly}
     */
    drawtype: null,
    /**
     * Currently drawn layer
     * @type {ol.layer.vector}
     */
    vectorlayer: null,
    
    drawInteraction : null,
    
     init: function() {
    
    	 	this.geojson = null;
    	 	this.drawtype = null;
    	 	
    	 	if(this.drawInteraction){
    	 		map.removeInteraction(this.drawInteraction);
    	 		this.drawInteraction = null;
    	 		if(!this.drawend){
    	 			this.sketch = null;
    	 		}    	 		
    	 	}  
    	 	this.drawend = false;
    	},
    
    ///初始化编辑图层
    setEditLayer: function(layer) {
    	 this.vectorlayer = null;
    	 if (layer instanceof ol.layer.Vector) {
    	 	this.vectorlayer = layer;
    	}
    },
    
     ///移除绘制状态
    removeDrawInteraction: function() {
    	if(this.drawend &&this.sketch){    	
         this.vectorlayer.getSource().removeFeature(this.sketch);
         this.sketch = null;
      }
    	this.init();   	
    },
    
    ///action draw
    createDrawInteraction: function(geomType) {
    	if(this.drawtype &&this.drawtype != geomType){
    			this.init();
    	}
    	this.drawtype = geomType;
    	if(this.drawInteraction){
    		return;
    	}
	    	if (geomType == 'Point') {
						this.drawInteraction = new ol.interaction.Draw({
	           							 		type: geomType,
	           									source: this.vectorlayer.getSource(),
	        										});
	        	
	        }else if(geomType == 'Line'){
	        	 this.drawInteraction = new ol.interaction.Draw({
	            									type: 'LineString',
	            									source: this.vectorlayer.getSource(),
	            									maxPoints: 20
	            								});
	        }else if (geomType == 'Polygon') {
	        	 this.drawInteraction = new ol.interaction.Draw({
	            												type: 'Polygon',
	            												source: this.vectorlayer.getSource()
	            											});
	        }       
					map.addInteraction(this.drawInteraction);
			
		
		 //var listener;
        this.drawInteraction.on('drawstart', function(evt) {
        	
        	measureUtil.clearLayer();
        	mapUtil.removeSelectSingleClick();
        	//删除上次的tmpe
          if(this.sketch){
          	this.vectorlayer.getSource().removeFeature(this.sketch);
          	this.sketch = null;
          }
          this.sketch = evt.feature;
          this.drawend = false;
          this.geojson = null;
          
          
            	
        }, this);
            
				this.drawInteraction.on('drawend', function(evt){
            var coordinate = evt.feature.getGeometry().getCoordinates();
            this.geojson= JSON.stringify(coordinate);
            //$('#coordinates').val(strify);//保存坐标
            //map.removeInteraction(drawgeom);
            //mapUtil.addSelectSingleClick();
            this.drawend = true;
        }, this);
		}    
};
